<?php
session_start();
$inspector = $_SESSION['user'];	//saves the current user as inspector for newly created files.
$isNewFile = 0; //global variable to determine if a new inspection has been created. 

//######################################################################################
//returns a list of available templates as an array of strings.
function listTemplates(){
	return array_map("trim", file("../files/templateList.txt"));
}

//######################################################################################
//readTemplate : String -> Array-of-strings
//takes a file name, opens the file, reads its comments and returns them as an array
function readTemplate($fileName){
	global $isNewFile;
	$isNewFile = 1;
	return file("../files/templates/$fileName");
}

//######################################################################################
//$string -> array[strings]
//read in a file from incompleteInspection folder.
function readIncomplete($fileName){
	$loadedFileName = $fileName;
	return file("../files/incompleteInspections/$fileName");
}

//######################################################################################
// String -> array[strings]
//loads a file from compltedInspetions folder.
function readComplete($fileName){
	return file("../files/completedInspections/$fileName");
}

//######################################################################################
//parseTemplateLines : Array-of-string -> Array-of-groups
//This function parses a file into the specified format below.
function parseTemplateLines($arrayOfStrings){
	global $inspector;
	//print_r($arrayOfStrings);
	$parsedTemplate = array(); // format ([fileInfo], [$arrayOfGroups])
	$fileInfo = array ();
	$arrayOfGroups = array();  // format ([groupArray], ...)
	$groupArray = array();  // format ([group Heading], [arrayOfQuestions])
	$arrayOfQuestions = array();//format ([questionArray] , ...)
	$questionArray = array(); //format ([question], [answer], [comment], [photo], [quesNum], [groupNum])
	
	$questionNum = 1;
	$groupNum = 1;
	$isFirstRun = true;  // skip adding empty group to array of Groups	
	foreach($arrayOfStrings as $element){
		if(substr($element, 0, 8) == "Facility"){
			$lineSplit = explode(":", $element);
			if(trim($lineSplit[1]) != ""){
				$fileInfo["facility"] = trim($lineSplit[1]);
			}
			else{
				$fileInfo["facility"] = trim($_REQUEST["facility"], "_");
			}
		}
		elseif(substr($element, 0, 4) == "Time"){
			$lineSplit = explode(":", $element);
			if(trim($lineSplit[1]) == ""){
				$fileInfo["time"] = date("g-iA");
			}
			else{
				//echo "time set from file";
				$fileInfo["time"] = trim($lineSplit[1]);
			}
		}
		elseif(substr($element, 0, 4) == "Date"){
			$lineSplit = explode(":", $element);
			if(trim($lineSplit[1]) == ""){
				$fileInfo["date"] = date("m-d-y");
			}
			else{
				$fileInfo["date"] = trim($lineSplit[1]);
			}
		}
		elseif(substr($element, 0, 8) == "Protocol"){
			$lineSplit = explode(":", $element);
			if(trim($lineSplit[1]) != ""){
				$fileInfo["protocol"] = trim($lineSplit[1]);
			}
			else{
				$fileInfo["protocol"] = trim($_REQUEST["protocol"]);
			}
		}
		elseif(substr($element, 0, 9) == "Inspector"){
			$lineSplit = explode(":", $element);
			//if inspector is empty than inspector = current user.
			if(trim($lineSplit[1]) != ""){
				$fileInfo["inspector"] = trim($lineSplit[1]);
			}
			else{
				$fileInfo["inspector"] = $inspector;
			}
		}
		elseif(substr($element, 0, 8) == "Complete"){
			$lineSplit = explode(":", $element);
			$fileInfo["complete"] = trim($lineSplit[1]);
		}
		//begin parsing groups
		//If first letter is 'G' and $isEnd is set to one then that means we have a new group.
		elseif(substr($element, 0, 1)=='G'){
			//adding $groupArray to $arrayOfGroups
			if($isFirstRun){
				//adding first group header
				$lineSplit = explode(":", $element);
				$groupArray["heading"] = trim($lineSplit[1]);
				$isFirstRun = false;
			}
			else{
			//save array of questions into group Array at position 1
				$groupArray["questions"] = $arrayOfQuestions;
				//reset arrayOfQuestions
				$arrayOfQuestions = array();
				//save group array into array of groups.
				array_push($arrayOfGroups, $groupArray);
				$groupArray = Null;
				$lineSplit = explode(":", $element);
				$groupArray["heading"] = trim($lineSplit[1]);
				$groupNum++;
				$questionNum = 1;
			}
		}
		elseif(substr($element, 0, 1)=="Q"){
			$lineSplit = explode(":", $element);
			//add question to array
			$questionArray["question"] = trim($lineSplit[1]);
		}
		elseif(substr($element, 0, 1)=="A"){
			$lineSplit = explode(":", $element);
			$questionArray["answer"] = trim($lineSplit[1]);
		}
		elseif(substr($element, 0, 1)=="C"){
			$lineSplit = explode(":", $element);
			$questionArray["comment"] = trim($lineSplit[1]);
		}elseif(substr($element, 0, 1)=="P"){
			$lineSplit = explode(":", $element);
			$questionArray["photo"] = trim($lineSplit[1]);
			$questionArray["quesNum"] = $questionNum;
			$questionArray["groupNum"] = $groupNum;
			//Add questionArray into array of questions and then set the array to Null for next round.
			array_push($arrayOfQuestions, $questionArray);
			$questionArray = array();
			//echo "this is the quesNum: $questionNum";
			$questionNum++;
		}
	}
	$groupArray["questions"] = $arrayOfQuestions;
	array_push($arrayOfGroups, $groupArray);
	$groupArray = array();
	$parsedTemplate["groups"]  = $arrayOfGroups;
	global $isNewFile;
	if($isNewFile == 0){
		$fileList = explode("_", $_REQUEST["file"]);
		if(isset($fileList[4])){
			$fileInfo["suffix"] = trim($fileList[4]);
		}
	} else{ $fileInfo["suffix"] = "";} //suffix does not exists.
	//add $isNewFile variable to fileInfo
	$fileInfo["isNewFile"] = $isNewFile;
	$parsedTemplate["fileInfo"] = $fileInfo;
	return $parsedTemplate;
}
//######################################################################################
//takes in $arrayOfGroups = ([groupArray], ...)
function loadTemplate($arrayOfGroups, $fileInfo){
	//print_r ($arrayOfGroups);
	$complete = $fileInfo["complete"];
	echo "<form action=\"saveView.php\" enctype=\"multipart/form-data\" method=\"post\">";
	foreach ($fileInfo as $name => $value) {
	?>
		<input type="hidden" name="<?= $name ?>" value="<?= $value ?>" />
	<?php
	}
	foreach($arrayOfGroups as $groupArray){
		renderGroup($groupArray, $complete);
	}
	if($complete != 1){
	?>
	<input type="submit" value="save" name="save"  />
	<input type="submit" value="submit Completed" action="checkComplete.php" name="save"  />
	
	<?php }
	echo "</form>";
}



//######################################################################################
//takes $groupArray = ([groupHeading], [arrayOfQuestions])
function renderGroup($groupArray, $complete){
	//print_r ($groupArray);
	$groupHeading = $groupArray["heading"];
	echo "<div class=\"heading\">$groupHeading</div>";
	echo "<ol>";
	foreach($groupArray["questions"] as $question){
		renderQuestion($question, $complete);
	}
	echo "</ol>";
}
//######################################################################################
// takes $question = ([question], [answer], [comment], [photo], [quesNum], [groupNum])
function renderQuestion($questionData, $complete){
	//print_r($questions);
	$question = $questionData["question"];
	echo "<li>";
		if(isset($_REQUEST["incomplete"])){
			$incomplete = $_REQUEST["incomplete"];
			//$incomplete = "r_1_4";
			$radioNum = "r_" . $questionData["groupNum"] . "_" . $questionData["quesNum"];
			//echo "Current RadioNum = $radioNum";
			//print(strpos($incomplete, $radioNum));
			//print(substr($incomplete, 0, 6));
			if(strpos($incomplete, $radioNum) != false || strpos($incomplete, $radioNum) != 0){
				echo "<p><font color=\"red\">$question</font></p>";
			} else{ echo "<p>$question</p>";}
		} else{ echo "<p>$question</p>";}
			echo "<span>";
			renderRadio(trim($questionData["answer"]), $questionData["quesNum"], $questionData["groupNum"], $complete);
	echo	"</span>
			<span>";
			renderComment(trim($questionData["comment"]), $questionData["quesNum"], $questionData["groupNum"], $complete);
			renderPhoto(trim($questionData["photo"]), $questionData["quesNum"], $questionData["groupNum"], $complete);
	echo	"</span>
		</li>";
}

//######################################################################################
function echoRadioButton($groupNum, $quesNum, $label, $isChecked = false, $isDisabled = false) {
	$userlabels = array( "y" => "Yes", "n" => "No", "_" => "N/a");
?>
	<input type="radio" class="radioButtons" name="r_<?= $groupNum . "_" . $quesNum ?>"
			id="<?= $label . "_" . $groupNum . "_" . $quesNum ?>" value="<?= $label ?>" 
			<?=   $isChecked ? "checked=\"checked\"" : "" ?>
			<?=   $isDisabled ? "disabled=\"true\"" : "" ?> />
	<label for="<?= $label . "_" . $groupNum . "_" . $quesNum ?>"><?= $userlabels[$label] ?></label>
<?php
}


//######################################################################################
//takes $answer = $string. either(y, n, "_", or "")
function renderRadio($answer, $quesNum, $groupNum, $complete){
	if($complete)
		echoRadioButton($groupNum, $quesNum, $answer, true, true);
	else{
		foreach (array("y", "n", "_") as $n) {
			echoRadioButton($groupNum, $quesNum, $n, $answer == $n);
		}
	}
}
//######################################################################################
//takes $comment = $string. supplied string for user if exists.
function renderComment($comment, $quesNum, $groupNum, $complete){
	$commentNum = "c_" . $groupNum . "_" . $quesNum;
	if($complete){
		if($comment == ""){
			//do nothing
		}
		else{ 
			?> <textarea rows="3" cols="50" readonly="true" id="<?=$commentNum?>" name= "<?=$commentNum ?>" > <?=$comment?> </textarea>
		<?php }
	}
	else{
		if($comment != ""){ ?>
			<textarea rows="3" cols"50" id="<?=$commentNum?>" name="<?=$commentNum?>"><?=$comment?></textarea>
		<?php }
		else{ ?>
			<script type="text/javascript">
				function createTextBox(commentNum){
					commentButton = document.getElementById(commentNum);
					newTextBox = document.createElement("TEXTAREA");
					newTextBox.setAttribute("name", commentNum);
					commentButton.parentNode.replaceChild(newTextBox, commentButton);
				}
			</script>
			<button type="button" id="<?=$commentNum?>" onclick='createTextBox("<?=$commentNum?>")' >Add Comment</button>
			
			<?php
		}
	}
}
//######################################################################################
//takes $photo = $string. loads a picture from the pictures folder.
function renderPhoto($photo, $quesNum, $groupNum, $complete){
	$photoNum = photoInputName($quesNum, $groupNum);
	if($complete == 1){
		if($photo == ""){
			//do nothing
		}
		else{ ?>
			<img src="../files/pictures/<?=$photo?>"/>
		<?php }
	}
	else{
		if($photo != ""){ ?>
			<a href="../files/pictures/<?=$photo?>" target="_blank">
			  <img src="../files/pictures/<?=$photo?>" width="75" height="75" />
			</a>
			<input type="hidden" name="<?=$photoNum?>" value="<?=$photo?>" />
		<?php }
		else{ ?>
			<script type="text/javascript">
				function addPhoto(photoNum){
					var photoButton = $(photoNum);
					var newPhoto = document.createElement("input");
					newPhoto.setAttribute("name", photoNum);
					newPhoto.setAttribute("id", photoNum);
					newPhoto.setAttribute("type", "file");
					photoButton.parentNode.replaceChild(newPhoto, photoButton);
					
					var delPhoto = document.createElement("input");
					delPhoto.setAttribute("name", 'del_' + photoNum);
					delPhoto.setAttribute("type", "button");
					delPhoto.setAttribute("id", "del_" + photoNum);
					delPhoto.setAttribute("value", "Delete");
					delPhoto.setAttribute("onClick", 'delButton("' + photoNum + '")');
					newPhoto.parentNode.appendChild(delPhoto);
				}
				
				function delButton(photoNum){
					var photoButton = $(photoNum);
					delPhoto = document.createElement("input");
					delPhoto.setAttribute("name", photoNum);
					delPhoto.setAttribute("id", photoNum);
					delPhoto.setAttribute("type", "button");
					delPhoto.setAttribute("value", "Add Photo");
					delPhoto.setAttribute("onclick", 'addPhoto("' + photoNum + '")');
					photoButton.parentNode.replaceChild(delPhoto, photoButton);
					
					var x = $("del_" + photoNum);
					x.parentNode.removeChild(x);
				}
			</script>
			<button type="button" id="<?=$photoNum?>" onclick='addPhoto("<?=$photoNum?>")' >Add Photo</button>
			
			<?php
		}
	}
}

function labeled_array_get($array, $key, $label) {
	return $label . ": " . $array[$key] . "\n";
}


// produces $array[$key] except if $key is not in the array, produces $default_value 
function array_get($array, $key, $default_value = "") {
	if (isset($array[$key])) return $array[$key];
	else return $default_value;
}

// generates the input element name for a radio button for the given question/group
function radioButtonName($quesNum, $groupNum) { return "r_{$groupNum}_{$quesNum}"; }

// generates the input element name for a radio button for the given question/group
function commentInputName($quesNum, $groupNum) { return "c_{$groupNum}_{$quesNum}"; }

// generates the input element name for a radio button for the given question/group
function photoInputName($quesNum, $groupNum) { return "p_{$groupNum}_{$quesNum}"; }


//######################################################################################
function test($input, $output){
	if($input===$output) {
		echo "passed";
	} else {
		echo "FAILURE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!";
	}
}

?>